import { AppContext } from "@/providers";
import { Form, FormInstance, Select, Image } from "antd";
import { cloneDeep } from "lodash";
import qs from "qs";
import { FC, RefObject, useContext, useEffect, useMemo, useState } from "react";
import { OperateGoodsContext } from "../../../../../OperateGoods";
import { SkuFormListItem } from "../../../SkuTable";

interface ValueListItem {
	image: string;
	name: string;
}
interface SkuSelectProps {
	formRef: RefObject<FormInstance>;
	index: number;
	setSkuFormList: (skuFormList: SkuFormListItem[]) => void;
	skuFormList: SkuFormListItem[];
}
//避免qs.stringify把name、image位置变换导致字符串值不一致的情况
export const getSkuValue = (name: string, image: string | null) => `name=${name}&image=${image || ""}`;
const SkuSelect: FC<SkuSelectProps> = ({ formRef, skuFormList, setSkuFormList, index }) => {
	const { skuOptions } = useContext(OperateGoodsContext);
	const [skuValueList, setSkuValueList] = useState<ValueListItem[]>([]);
	const { REACT_APP_BASEURL } = useContext(AppContext);
	useEffect(() => {
		const { key, value } = skuFormList[index];
		formRef.current?.setFieldsValue({ key, value });
		const list = (skuOptions.find((item) => item.key === key)?.valueList || []).map(({ name, image }) => ({
			image: image || "",
			name,
		}));
		setSkuValueList(list);
	}, [skuFormList, skuOptions]);
	const selectedKeys = useMemo<string[]>(() => {
		return skuFormList.filter((item) => typeof item.key === "string").map((item) => item.key) as string[];
	}, [skuFormList]);
	return (
		<Form ref={formRef} labelCol={{ span: 3 }} wrapperCol={{ span: 8 }}>
			<Form.Item label="sku类型" name="key" rules={[{ required: true, message: "请选择sku类型" }]}>
				<Select
					placeholder="请选择sku类型"
					options={skuOptions
						.filter((item) => !selectedKeys.includes(item.key))
						.map((item) => ({ label: item.key, value: item.key }))}
					value={skuFormList[index].key}
					onChange={(key) => {
						formRef.current?.setFieldValue("value", null);
						const copiedList = cloneDeep(skuFormList);
						copiedList[index] = {
							...copiedList[index],
							key,
							value: null,
						};
						setSkuFormList(copiedList);
					}}
				/>
			</Form.Item>
			<Form.Item label="sku值" name="value" rules={[{ required: true, message: "请选择sku值" }]}>
				<Select
					placeholder="请选择sku值（多选）"
					value={skuFormList[index].value}
					onChange={(valueObject) => {
						const { name = "", image = null } = qs.parse(valueObject) as { name: string; image: string | null };
						const copiedList = cloneDeep(skuFormList);
						copiedList[index].value = getSkuValue(name, image);
						setSkuFormList(copiedList);
					}}
					options={skuValueList.map(({ name, image }) => ({
						label: (
							<div className="flex">
								{image && (
									<div className="mr-2">
										<Image height={25} width={30} style={{ objectFit: "cover" }} src={`${REACT_APP_BASEURL}${image}`} />
									</div>
								)}
								<div>{name}</div>
							</div>
						),
						value: getSkuValue(name, image),
					}))}
				/>
			</Form.Item>
		</Form>
	);
};

export default SkuSelect;
